package cn.itmtr.screenshot.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;

import java.io.IOException;

/**
 * 网页截图服务类
 *
 * @author mtr
 * @since 2021-09-24
 */
public interface IScreenshotService {

    /**
     * 获取默认存储地址
     *
     * @return java.lang.String
     * @author mtr
     * @date 2021/9/24
     */
    String getImageDefaultPath();

    /**
     * 获取默认存储地址
     *
     * @return java.lang.String
     * @author mtr
     * @date 2021/9/24
     */
    String getPhantomjsCmd();

    /**
     * 创建执行命令
     *
     * @param url       网址
     * @param imagePath 图片存储地址
     * @return java.lang.String
     * @author mtr
     * @date 2021/9/24
     */
    default String createExecutionCommand(String url, String imagePath) {
        String cmd = StrUtil.format("{} {} {} 1440px*960px", this.getPhantomjsCmd(), url, imagePath);
        StaticLog.info("执行语句：{}", cmd);
        return cmd;
    }

    /**
     * 生成网址jiet
     *
     * @param url       网址
     * @param imagePath 图片地址 可不填
     * @author mtr
     * @date 2021/9/24
     */
    default void screenshot(String url, String imagePath) {
        if (StrUtil.isBlank(imagePath)) {
            imagePath = this.getImageDefaultPath();
            StaticLog.info("未传入图片地址，自动生成：{}", imagePath);
        }
        String cmd = createExecutionCommand(url, imagePath);
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            // 执行结果
            FileUtil.writeFromStream(process.getInputStream(), imagePath);
        } catch (IOException e) {
            StaticLog.error("保存网址截图失败：", e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
    }

}
